﻿<template>
	<full-screen-dialog :title="titleMap[mode]" v-model="visible" :width="1200" destroy-on-close
		@closed="$emit('closed')">

		<el-form :model="entityObj" :rules="rules" :disabled="mode == 'Show'" ref="dialogForm" label-width="100px">


			<el-steps :active="1" align-center finish-status="success">
				<el-step title="集采已下单" description="" />
				<el-step title="供应商处理中" description="" />
				<el-step title="已完成" description="" />
			</el-steps>

			 <!--补发、退货--->
			 <el-row style="margin-top: 18px;" >
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="订单类型:">{{entityObj.purchaseOrderType==1?"补发":"退货"}}</el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="单据状态:">{{entityObj.statusDesc}}</el-form-item>
                    </el-col>
                
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="物料发货状态:">{{entityObj.purchaseOrderType==1?entityObj.sendStatusDesc:"无需发货"}}</el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="接单金额:">{{entityObj.receiveAmount}}</el-form-item>
                    </el-col>
            </el-row>
            <el-row>
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="订单编号:">{{entityObj.purchaseOrderCode}}</el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="申请单位:">
                            <el-tooltip placement="top">
                                <template #content>
                                    联系人: {{entityObj.realName}}
                                    <br />
                                    联系电话:{{entityObj.mobile}}
                                    <br />
                                    收货地址:{{entityObj.address}}
                                </template>
                                <span style="color: blue;">{{entityObj.storeName}}</span>
                            </el-tooltip>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="下单人:">{{entityObj.createName}}</el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="下单时间:">{{entityObj.createTime}}</el-form-item>
                    </el-col>
            </el-row>
            <el-row>
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="采购单位:">
                        <el-tooltip placement="top">
                            <template #content>
                                联系人: {{entityObj.purchaseUnityRealName}}
                                <br />
                                联系电话:{{entityObj.purchaseUnityMobile}}
                                <br />
                                联系地址:{{entityObj.purchaseUnityAddress}}
                            </template>
                            <span style="color: blue;">{{entityObj.purchaseUnityName}}</span>
                        </el-tooltip>
                    </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="120px" label="供应商:">
                            <el-tooltip placement="top">
                                <template #content>
                                    联系人: {{entityObj.supplierRealName}}
                                    <br />
                                    联系电话:{{entityObj.supplierMobile}}
                                    <br />
                                    收货地址:{{entityObj.supplierAddress}}
                                </template>
                                <span style="color: blue;">{{entityObj.supplierName}}</span>
                            </el-tooltip>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      
                    </el-col>
                    <el-col :span="6">
                       
                    </el-col>
            </el-row>
			
			<!-- <el-row>
				<el-col :span="24">
					<el-form-item label-width="120px" label="下单备注:">
						{{entityObj.remarks}}
					</el-form-item>
				</el-col>
			</el-row> -->
			<el-row>
                <el-col :span="6" v-if="entityObj.purchaseOrderItems" style="color:red">
                    <el-form-item label-width="120px" label="集采确认数量:">{{entityObj.purchaseOrderItems[0].confirmQty}}</el-form-item>
                </el-col>
                <el-col :span="6" v-if="entityObj.purchaseOrderItems" style="color:red">
                    <el-form-item label-width="120px" label="集采确认备注:">{{entityObj.purchaseOrderItems[0].confirmRemarks}}</el-form-item>
                </el-col>
            </el-row>
			<el-row>
				<el-col :span="24">
					<el-form-item label-width="120px" :label="itemName">
						<el-table :data="entityObj.purchaseOrderItems" border style="width: 100%" show-summary
							:summary-method="getSummaries">
							<el-table-column label="物料编码" min-width="130" prop="materialCode"></el-table-column> 
						
							<el-table-column label="物料名称" min-width="200" prop="materialName">
								<template #default="scope">
                                        <div style="color: #318cf2; cursor: pointer;" @click="handlePreview(scope.row)">
                                            {{scope.row.materialName}}
                                        </div>
                                    </template>
							</el-table-column>
							<el-table-column label="分类" min-width="130" prop="materialTypeName"></el-table-column> 
							<el-table-column label="规格" min-width="120" prop="materialSpecs"></el-table-column>
							<el-table-column label="单位" min-width="95" prop="unitName"></el-table-column>
							<el-table-column label="采购单价" min-width="120" prop="price">
							</el-table-column>
							<el-table-column label="集采下单数量" min-width="120" prop="confirmQty"></el-table-column>
							<el-table-column label="实际接单数量" min-width="160" prop="receiveQty">
								<template #default="scope">
									<el-input-number v-model="scope.row.receiveQty" :max="scope.row.confirmQty"
										style="width: 100%" :step="1"></el-input-number>
								</template>
							</el-table-column>
							<el-table-column label="附件" min-width="150">
								<template #default="scope">
                                        <sc-upload-multiple 
                                            v-model="scope.row.afterAttachment"
                                            :objName="'Supply/AfterOrder'" 
                                            :uploadType="'OSS'" 
                                            :bucketName="'jtmc'" 
                                            :limit="1"/>
                                    </template>
							</el-table-column>
							<el-table-column label="门店要货编号" width="160" prop="applyOrderCode">
                                    <template #default="scope"> 
                                        <span v-if="entityObj.applyOrderId!=0">{{entityObj.applyOrderCode}}</span>
                                        <span v-else>无</span>
                                    </template>
                                </el-table-column>
							<el-table-column label="接单备注" min-width="200">
								<template #default="scope">
									 <el-input
                                        v-model="scope.row.receiveRemarks"
                                        style="width: 100%"
                                        :step="1"
                                    ></el-input>
								</template>
							</el-table-column>

							
						</el-table>
					</el-form-item>
				</el-col>
			</el-row>
			
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">接 单</el-button>
		</template>
		  <!-- 预览组件 -->
		  <el-image-viewer v-if="showImage" @close="closeViewer" :url-list="srcList" />
	</full-screen-dialog>
</template>



<script>
	import tool from "@/utils/tool";
	export default {
		emits: ["success", "closed"],
		data() {
			return {
				mode: "Add",
				titleMap: {
					Add: "新增",
					Edit: "编辑",
					Show: "查看",
				},
				entityObj: {
					purchaseProtocolId: 0,
					purchaseProtocolCode: "",
					purchaseProtocolName: "",
					status: 1,
					crName: "",
					crDate: "",
					supplier: {},
					protocolDate: [],
					purchaseUnityName: "",
					SupplierRemarks:"",
					remarks: "",
					protocolFile: "",
					purchaseProtocolItems: [],
				},
				materialState: false,
				queryList: {},
				visible: false,
				isSaveing: false,
				needSaveFlag: false,
				//验证规则
				rules: {
					purchaseProtocolName: [{
						required: true,
						type: "string",
						message: "请填写"
					}, ],
					purchaseUnityName: [{
						required: true,
						type: "string",
						message: "请填写"
					}, ],
					supplier: [{
						required: true,
						type: "object",
						message: "请填写"
					}, ],
					protocolDate: [{
						required: true,
						type: "array",
						message: "请填写"
					}, ],
					crName: [{
						required: true,
						type: "string",
						message: "请填写"
					}],
					crDate: [{
						required: true,
						type: "string",
						message: "请填写"
					}],
					materialSpecs: [{
						required: true,
						type: "string",
						message: "请填写"
					}, ],
					purchaseProtocolItems: [{
						required: true,
						type: "array",
						message: "请填写",
						trigger: "change",
					}, ],
				},
				props: {
					label: "supplierName",
					value: "supplierId",
				},
				materialProps: {
					label: "materialCode",
					value: "materialId",
					items: "materialItems",
				},
				materialTypeTree: [],
				optionsBrand: [],
				optionsUnit: [],
				itemsData: [],
				itemName:"应发货清单:",
				  //预览图片
				  previewUrl: [],
				//预览图片列表
				srcList: [],
				showImage: false,
			};
		},
		computed: {
			// itemsData() {
			//     let filtered = this.entityObj.purchaseProtocolItems;
			//     if (this.queryList.materialTypeIds&&this.queryList.materialTypeIds.length>0) {
			//         filtered = filtered.filter(item => {
			//             return this.queryList.materialTypeIds.includes(item.materialTypeId);
			//         });
			//     }
			//     if (this.queryList.materialCode) {
			//         filtered = filtered.filter(item => {
			//             return item.materialCode.includes(this.queryList.materialCode);
			//         });
			//     }
			//     if (this.queryList.materialName) {
			//         filtered = filtered.filter(item => {
			//             return item.materialName.includes(this.queryList.materialName);
			//         });
			//     }
			//     return filtered;
			// },
		},
		methods: {
			//显示=
			open(mode = "Add") {
				this.mode = mode;
				this.visible = true;
				return this;
			},
			//表单提交方法
			submit() {
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						try {
							var returnValue =
								await this.$API.auth.PostProcessApi.post("purchase-order/after-receive", {
									...this.entityObj
								});
							if (returnValue.status == 200) {
								this.$message.success("操作成功");
								this.$emit("fatherMethod");
								this.isSaveing = false;
								this.visible = false;
							} else {
								this.$message.error("操作失败:" + returnValue.msg);
								this.isSaveing = false;
							}
						} catch (error) {
							this.loading = false;
							this.isSaveing = false;
							return false;
						}
					}
				});
			},
			//表单注入数据
			async setData(data) {
				if(data.purchaseOrderType==1)
				{
					this.itemName="补发清单:";
					this.titleMap.Add="接单";
				}else  if(data.purchaseOrderType==2)
				{
					this.itemName="退货清单:";
					this.titleMap.Add="接单";
				}
				data.purchaseOrderItems.map(p => p.receiveQty = p.qty);
				this.entityObj = {
					...data,
					purchaseOrderItems: data.purchaseOrderItems
				};
				console.log(this.entityObj)
			},
			async initOptions() {
				try {
					var returnValue = await this.$API.auth.PostProcessApi.post(
						"material-type/tree", {
							status: 1
						}
					);
					if (returnValue.status == 200) {
						this.materialTypeTree = returnValue.response;
					} else {
						this.$message.error("操作失败:" + returnValue.msg);
					}
				} catch (error) {
					this.loading = false;
					return false;
				}
			},
			async supplierSelectProcess(rowData) {
				this.entityObj.supplier = {};
				if (rowData) {
					this.entityObj.supplier = {
						supplierId: rowData.supplierId,
						supplierName: rowData.supplierName,
					};
				}
				console.log(this.entityObj.supplier);
			},
			addMaterial() {
				this.materialState = true;
			},
			deleteRow(index) {
				this.entityObj.purchaseProtocolItems.splice(index, 1);
			},
			handleSearch() {
				this.itemsData = this.entityObj.purchaseProtocolItems;
				if (
					this.queryList.materialTypeIds &&
					this.queryList.materialTypeIds.length > 0
				) {
					this.itemsData = this.itemsData.filter((item) => {
						return this.queryList.materialTypeIds.includes(
							item.materialTypeId
						);
					});
				}

				if (this.queryList.materialCode) {
					this.itemsData = this.itemsData.filter((item) => {
						return item.materialCode.includes(
							this.queryList.materialCode
						);
					});
				}

				if (this.queryList.materialName) {
					this.itemsData = this.itemsData.filter((item) => {
						return item.materialName.includes(
							this.queryList.materialName
						);
					});
				}
				console.log(this.entityObj.purchaseProtocolItems);
			},
			setMaterialChoice() {
				let materials = this.$refs.scMaterialChoice.selectionRows;
				materials.map((p) => {
					this.entityObj.purchaseProtocolItems.push({
						materialId: p.materialId,
						materialCode: p.materialCode,
						materialName: p.materialName,
						materialSpecs: p.materialSpecs,
						materialTypeId: p.materialTypeId,
						materialTypeName: p.materialTypeName,
						unitCode: "",
						unitName: "",
						price: 0.0,
						remarks: "",
						materialItemId: null,
						materialItems: p.materialItems,
					});
				});
				this.materialState = false;
				this.queryList = {};
				this.handleSearch();
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			getSummaries(param) {
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '合计'
						return;
					}
					const values = data.map(item => Number(item[column.property]));

					if (column.property == 'confirmQty' || column.property == 'totalAmount') {
						if (!values.every(item => isNaN(item))) {
							const total = values.reduce((a, b) => a + b, 0)
							sums[index] = total
						}
					}
				});
				return sums;
			},
			 //图片预览
			 handlePreview(row) {
				if (!row.materialImages || row.materialImages.length == 0) {
					return;
				}
				this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
				this.srcList = row.materialImages; // 设置预览列表
				this.showImage = true; // 显示 el-image

			},
			closeViewer(){
				this.showImage = false; 
			},
		},
		async mounted() {
			this.entityObj.purchaseUnityName = tool.data.get("USER_INFO").OrgName;
			this.entityObj.crName = tool.data.get("USER_INFO").Name;
			this.entityObj.crDate = this.formatDate(new Date());
			await this.initOptions();
		},
	};
</script>

<style scoped>
	.el-form-item {
		margin-bottom: 5px !important;
	}
	/deep/ .el-upload--picture-card{
    width: 50px;
    height: 50px;
}
/deep/ .el-upload{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail{
    width: 50px;
    height: 50px;
    line-height: 50px;
}
</style>
